package com.atguigu.gmall.list.controller;

import com.atguigu.gmall.common.result.Result;
import com.atguigu.gmall.list.service.ListService;
import com.atguigu.gmall.model.list.Goods;
import com.atguigu.gmall.model.list.SearchParam;
import com.atguigu.gmall.model.list.SearchResponseVo;
import io.swagger.annotations.Api;
import org.elasticsearch.client.IndicesClient;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.client.indices.CreateIndexRequest;
import org.elasticsearch.client.indices.GetIndexRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.data.elasticsearch.core.ElasticsearchTemplate;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;

/**
 * @author 李旭
 * @date 2022/1/12 10:05
 * @Description:
 *
 *   创建索引库
 *   Mappings映射
 *   保存索引数据
 *   搜索索引
 *
 */
@RestController
@RequestMapping("/api/list")
@Api(tags = "搜索微服务")
public class ListApiController {


    //ES官方客户端  DSl
    @Autowired
    private RestHighLevelClient restHighLevelClient;//高级 性能高  查询
    //Spring封装的
    @Autowired
    private ElasticsearchRestTemplate elasticsearchRestTemplate;//封装高级 性能稍微低

    @Autowired
    private ListService listService;
    //@Autowired
    //private ElasticsearchTemplate elasticsearchTemplate;//低级


    //创建索引库
    @GetMapping("/createIndex")
    public Result createIndex(){
        //创建索引库
        //elasticsearchRestTemplate.createIndex("goods");
        elasticsearchRestTemplate.createIndex(Goods.class);
        // Mappings映射
        elasticsearchRestTemplate.putMapping(Goods.class);

 /*       IndicesClient indices = restHighLevelClient.indices();
        GetIndexRequest getIndexRequest = new GetIndexRequest("goods");
        try {
            indices.exists(getIndexRequest, RequestOptions.DEFAULT);
        } catch (IOException e) {
            e.printStackTrace();
        }*/

        return Result.ok();
    }
    //上架  添加索引
    @PostMapping("/onSale/{skuId}")
    public Result onSale(@PathVariable Long skuId){
        listService.onSale(skuId);
        return Result.ok();
    }

    //下架  删除索引
    @DeleteMapping("/cancelSale/{skuId}")
    public Result cancelSale(@PathVariable Long skuId){
        listService.cancelSale(skuId);
        return Result.ok();
    }

    //商品热度排序  （ 加分的接口）
    @GetMapping("/hotScore/{skuId}/{score}")
    public Result hotScore(@PathVariable Long skuId,@PathVariable Long score){
        //加分
        listService.hotScore(skuId,score);

        return Result.ok();
    }

    //开始搜索
    @PostMapping
    public SearchResponseVo list(@RequestBody SearchParam searchParam){
        return listService.list(searchParam);
    }

}
